package etl.util;

import util.UserAgentParser;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class LogParserUtil {
    public static Map LogParser(String log) {
        Map<String, String> buffer = new HashMap<String, String>();
        String[] fields = log.split("\\?");
        String ip = fields[0].split("\\^A")[0];
        String s_time = fields[0].split("\\^A")[1];
        buffer.put("ip", ip);
        buffer.put("s_time", s_time);
        IPParser.RegionInfo regionInfo = IPParser.localParser(ip);
        buffer.put("country", regionInfo.getCountry());
        buffer.put("city", regionInfo.getCity());
        buffer.put("province", regionInfo.getProvince());

        String request[] = fields[1].split("&");
        for (String s : request) {
            String kv[] = s.split("=");
            String k = kv[0];
            String v = null;
            try {
                v = URLDecoder.decode(kv[1], "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            buffer.put(k, v);
        }
        String UA = buffer.get("b_iev");
        UserAgentParser.AgentInfo agentInfo = UserAgentParser.parserUA(UA);
        buffer.put("browserName", agentInfo.getBrowserName());
        buffer.put("browserVersion", agentInfo.getBrowserVersion());
        buffer.put("osName", agentInfo.getOsName());
        buffer.put("osVersion", agentInfo.getOsVersion());
        return buffer;
    }

}
